class QuestionnaireEvent < ActiveRecord::Base
	belongs_to :questionnaire
	belongs_to :questionnaire_event_type

  before_create :validate_status
	after_create :update_data_collections
  after_destroy :update_data_collections



  private

  def validate_status
		if (self.questionnaire_event_type.name == "Other" && self.comment.empty?)
			errors.add(nil, "Status was not saved! When using status 'Other', make sure to include a comment.")
      return false
		end

    self.questionnaire.questionnaire_events.reverse.each do |e|

      if (!self.questionnaire_event_type.rank.nil? && !e.questionnaire_event_type.rank.nil? &&
            self.questionnaire_event_type.rank <= e.questionnaire_event_type.rank)
				errors.add(nil, format("Status was not saved! Status '%s' cannot succeed existing status '%s'.",
            self.questionnaire_event_type.name, e.questionnaire_event_type.name))
        return false
			end
    end

  end



  def update_data_collections
    self.questionnaire.data_collection.youth.update_data_collections
  end

	# What the heck is this code doing in this class? Well...
	# This is the only way to know when to start T3, by checking when the first
	# action is taken on the T1 data collection.
  #	def create_data_collections
  #		if (self.questionnaire.data_collection.data_collection_wave.name == (DataCollectionWave::T1) &&
  #			!self.questionnaire.data_collection.youth.has_t3 &&
  #			(self.questionnaire.questionnaire_name.name == QuestionnaireName::YOUTH ||
  #			self.questionnaire.questionnaire_name.name == QuestionnaireName::PARENT) &&
  #			(self.questionnaire_event_type.name == QuestionnaireEventType::FILLED_OUT_BY_RESPONDENT ||
  #			self.questionnaire_event_type.name == QuestionnaireEventType::FILLED_OUT_BY_INTERVIEWER))
  #				self.questionnaire.data_collection.youth.create_data_collections_t3_t4(self.created_at.to_time.advance(:years => 1))
  #		end
  #	end
end
